<template>
  <div class="nmc-manage">
    <card>
      <!-- 操作按钮 -->
      <div class="mb-4">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="danger" @click="handleDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </div>

      <!-- ElementTable组件 -->
      <ElementTable
        :data="nmcDevices"
        :tableTitle="tableColumns"
        :showPagination="false"
        :pageConfig="pageConfig"
        @selectChange="handleSelectChange"
        @selectBox="handleSelectBox"
        @selectAll="handleSelectAll"
      />
    </card>

    <!-- NMC设备对话框 -->
    <ServerDialog
      ref="serverDialogRef"
      :visible="dialogVisible"
      :isEditMode="isEditMode"
      :serverData="currentServerData"
      :title="isEditMode ? '修改NMC' : '新增NMC'"
      @update:visible="dialogVisible = $event"
      @close="handleDialogClose"
      @save="handleSave"
    />

    <!-- 源节点列表对话框 -->
    <SourceNodesDialog
      :visible="sourceNodesDialogVisible"
      :title="`${currentServerData?.name || ''} - 流媒体列表`"
      :serverId="currentServerData?.id?.toString() || ''"
      @update:visible="sourceNodesDialogVisible = $event"
      @close="handleSourceNodesDialogClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElButton, ElIcon } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { success, error, warning } from '@/utils/toast'
import { confirm } from '@/utils/confirm'
import { $getAllServer, $deleteServer, $addServer, $editServer } from '@/api/nvr'
import type { StreamServer } from '@/types'
import ServerDialog from '../stream/components/ServerDialog.vue'
import SourceNodesDialog from '@/components/SourceNodesDialog.vue'

// 数据
const nmcDevices = ref<StreamServer[]>([])
const selectedRows = ref<StreamServer[]>([])
const loading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentServerData = ref<StreamServer | null>(null)
const serverDialogRef = ref()

// 源节点对话框状态
const sourceNodesDialogVisible = ref(false)

// 分页配置
const pageConfig = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper',
  total: 0,
  background: true,
  handleSizeChange: (size: number) => {
    pageConfig.pageSize = size
    pageConfig.currentPage = 1
    loadData()
  },
  handleCurrentChange: (page: number) => {
    pageConfig.currentPage = page
    loadData()
  }
})

// 表格列配置
const tableColumns = ref([
  {
    type: 'selection',
    width: '50'
  },
  {
    type: 'text',
    label: '名称',
    prop: 'name',
  },
  {
    type: 'text',
    label: 'IP',
    prop: 'ip',
  },
  {
    type: 'text',
    label: '端口',
    prop: 'port',
  },
  {
    type: 'text',
    label: '用户名',
    prop: 'userName',
  },
  {
    type: 'text',
    label: '密码',
    prop: 'password',
  },
  {
    type: 'status',
    label: '在线状态',
    prop: 'online',
    options: [
      { value: true, text: '在线', type: 'success' },
      { value: false, text: '离线', type: 'danger' }
    ]
  },
  {
    type: 'operate',
    label: '操作',
    width: '200',
    actions: [
      {
        name: '查看',
        isLink: true,
        click: (row: StreamServer) => handleView(row),
        type: 'primary',
        size: 'small',
      },
      {
        name: '修改',
        type: 'primary',
        size: 'small',
        isLink: true,
        click: (row: StreamServer) => handleEdit(row)
      },
      {
        name: '删除',
        type: 'danger',
        size: 'small',
        isLink: true,
        notNeedAuto: true,
        click: (row: StreamServer) => handleDeleteSingle(row)
      }
    ]
  }
])

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const response = await $getAllServer(2) // type=2 获取NMC数据
    console.log("🚀 ~ file: index.vue:138 ~ response:", response)
    nmcDevices.value = response.data || []
    pageConfig.total = response.count || 0
  } catch (err) {
    console.error('获取NMC数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 选择变化处理
const handleSelectChange = (selection: StreamServer[]) => {
  selectedRows.value = selection
}

const handleSelectBox = (selection: StreamServer[]) => {
  selectedRows.value = selection
}

const handleSelectAll = (selection: StreamServer[]) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  isEditMode.value = false
  currentServerData.value = null
  dialogVisible.value = true
}

// 批量删除
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    warning('请选择要删除的数据')
    return
  }
  
  try {
    await confirm.batch('删除', selectedRows.value.length, 'NMC设备')
    
    const deletePromises = selectedRows.value.map(item => 
      $deleteServer(item.id!)
    )
    await Promise.all(deletePromises)
    success('删除成功')
    selectedRows.value = []
    loadData()
  } catch (err) {
    if (err !== 'cancel') {
      error('删除失败')
      console.error('删除失败:', err)
    }
  }
}

// 单个删除
const handleDeleteSingle = async (row: StreamServer) => {
  try {
    await confirm.delete(row.name, 'NMC设备')
    
    await $deleteServer(row.id!)
    success('删除成功')
    loadData()
  } catch (err) {
    if (err !== 'cancel') {
      error('删除失败')
      console.error('删除失败:', err)
    }
  }
}


const handleView = (row: StreamServer) => {
  console.log('查看源节点:', row)
  currentServerData.value = row
  sourceNodesDialogVisible.value = true
}

// 编辑
const handleEdit = (row: StreamServer) => {
  isEditMode.value = true
  currentServerData.value = row
  dialogVisible.value = true
}

// 保存NMC设备
const handleSave = async (data: Partial<StreamServer>) => {
  try {
    if (isEditMode.value) {
      // 编辑模式
      const res = await $editServer(data.id ?? 0, data.name ?? '')
      success(`${res.msg}`)
    } else {
      // 新增模式，添加type字段标识为NMC
      const addData = { ...data, type: 2 } as StreamServer
      const res = await $addServer(addData)
      success(`${res.msg}`)
    }
    // 关闭对话框
    dialogVisible.value = false
    // 重新加载数据
    loadData()
  }finally {
    // 重置对话框loading状态
    serverDialogRef.value?.resetLoading()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  currentServerData.value = null
}

// 关闭源节点对话框
const handleSourceNodesDialogClose = () => {
  sourceNodesDialogVisible.value = false
  currentServerData.value = null
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.nmc-manage {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>